import os
import cookielib
import urllib2
import urllib
import httplib
import re

httplib.HTTPConnection.debuglevel = 1

# Thank you: http://diveintopython.org/http_web_services/redirects.html 
class SmartRedirectHandler(urllib2.HTTPRedirectHandler, cookielib.LWPCookieJar):
	def http_error_301(self, req, fp, code, msg, headers):
		result = urllib2.HTTPRedirectHandler.http_error_301(
			self, req, fp, code, msg, headers)
		result.status = code
		print "301 " + msg 
		return result

	def http_error_302(self, req, fp, code, msg, headers):
		result = urllib2.HTTPRedirectHandler.http_error_302(
			self, req, fp, code, msg, headers)
		result.status = code

		print "302 " + msg
		return result

####################################
# Simple Hi5 API 
# Create by wearetherock@gmail.com
# Sat Sep 26, 12:16 AM
####################################
class Hi5Api :
	# install cookie to urllib2
	def __init__(self,email, password) :	
		COOKIE_FILE = "cookie.lwp"
		#cj = SmartRedirectHandler()
		cj = cookielib.LWPCookieJar()

		if os.path.isfile(COOKIE_FILE):
			cj.load(COOKIE_FILE)
		if cookielib :
			opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
			urllib2.install_opener(opener)

		page = self.login(email, password)

		# testing section
		f = open("hi5login.html", "w")
		f.write(page)
		f.close()

		#self.id = self.getTimeStamp(page)
		#cj.save(COOKIE_FILE)

	# have to include timestamp beside body message
	def getTimeStamp(self, page):
		post_url = "http://www.hi5.com/friend/profile/displaySameProfile.do?userid=" + "157658571" #your id
		body = {}
		headers = { 
			"Accept" : "*/*", 
			"Content-type" : "application/x-www-form-urlencoded" ,
			"User-agent": "Mozila/4.0"}

		req = urllib2.Request(post_url, data = urllib.urlencode(body), headers = headers)
		handle = urllib2.urlopen(req)
		content = handle.read()

		id_pat = r"""name="userid" value="(.+?)">"""
		time_pat = r'''name="timestamp" value="(.+?)">'''
		js_pat = r'''name="js" value="(.+?)">'''

		# compile many time, not good pleas fix it
		user_id = re.compile(id_pat).findall(content)[0]
		time = re.compile(time_pat).findall(content)[0]
		js = re.compile(js_pat).findall(content)[0]
					
		return user_id, time, js

	# post into your own profile not other
	def postHi5(self, message):
		user_id, time, js = self.getTimeStamp("")

		post_url = "http://www.hi5.com/friend/profile/signBook.do"
		headers = { "Content-type" : "application/x-www-form-urlencoded",
					"User-agent" : "Mozila/4.0" }
		body = { "body" : message, "js" : js ,
					"userid" : user_id,
					"userId" : user_id,
					"timestamp" : time }
		req = urllib2.Request(post_url, data = urllib.urlencode(body), headers = headers)
		handle = urllib2.urlopen(req)
		content = handle.read()

	def login(self,email, password) :
		the_url = "http://www.hi5.com/friend/login.do"
		tx_data = {
				"email" : email ,
				"password" : password,
				"remember" : "true"} 
		tx_headers = { 
				"User-agent" : "Mozilla/4.0",
				"Content-type" : "application/x-www-form-urlencoded" }

		req = urllib2.Request(the_url, data = urllib.urlencode(tx_data), headers = tx_headers)
		handle = urllib2.urlopen(req)
		return handle.read()

if __name__ == "__main__" :
	email = ""
	password = ""
	h = Hi5Api(email, password)
	h.postHi5("Something FooBar Hey Hey..")
